#include <malloc.h>
#include "clib_memory_allocator_standard.h"

//全局标准内存分配器
static struct clib_memory_allocator global_standard_allocator = {0};
static int global_standard_allocator_init_flag = 0;

static void *standard_allocator_malloc(clib_uint64_t size) {
    clib_check_if_true_return_value(size <= 0, NULL);
    return malloc(size);
}

//re_alloc 函数声明
static void *standard_allocator_re_alloc(void *data, clib_uint64_t size) {
    clib_check_if_true_return_value(data == NULL || size <= 0, NULL);
    return realloc(data, size);
}

//free 函数声明
static void standard_allocator_free(void *data) {
    clib_check_if_true_return(data == NULL);
    free(data);
}

//clear 函数声明
static void standard_allocator_clear() {

}

//exit 函数声明
static void standard_allocator_exit() {

}

//拷贝 函数声明
static void standard_mem_copy(void *target, void *src, size_t length) {
    memcpy(target, src, length);
}

int clib_memory_allocator_standard_init() {
    //标准分配器类型
    global_standard_allocator.type = CLIB_ALLOCATOR_TYPE_STANDARD;
    //没有使用锁
    global_standard_allocator.flag |= CLIB_ALLOCATOR_FLAG_NO_USE_LOCK;
    //malloc函数
    global_standard_allocator.malloc = standard_allocator_malloc;
    //re_alloc函数
    global_standard_allocator.re_alloc = standard_allocator_re_alloc;
    //free函数
    global_standard_allocator.free = standard_allocator_free;
    //clear函数
    global_standard_allocator.clear = standard_allocator_clear;
    //exit函数
    global_standard_allocator.exit = standard_allocator_exit;
    //内存拷贝
    global_standard_allocator.mem_copy = standard_mem_copy;
    //标记已经成功初始化
    global_standard_allocator_init_flag = 1;
    return CLIB_RES_OK;
}

struct clib_memory_allocator *clib_memory_allocator_standard_get() {
    clib_check_if_true_return_value(global_standard_allocator_init_flag == 0, NULL);
    return &global_standard_allocator;
}